package com.example.myapplication.vision.idcard.activity;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;


import com.example.myapplication.vision.idcard.utils.Camera2Proxy;

/**
 * Create By TreeRoot
 * Create Time: 2024/01/24 09:45
 * Class Name: Camera2View
 * Description:
 * 相机预览View
 *
 * @author TreeRoot
 */
public class Camera2View extends TextureView {

    /**
     * 相机代理
     */
    private Camera2Proxy mCameraProxy;
    /**
     * 预览宽高比
     */
    private int mRatioWidth = 0;
    /**
     * 预览宽高比
     */
    private int mRatioHeight = 0;


    public Camera2View(Context context) {
        this(context, null);
    }

    public Camera2View(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Camera2View(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public Camera2View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    /**
     * 获取相机代理
     *
     * @return 相机代理
     */
    public Camera2Proxy getCameraProxy() {
        return mCameraProxy;
    }

    /**
     * 初始化
     *
     * @param context 上下文
     */
    private void init(Context context) {
        mCameraProxy = new Camera2Proxy((Activity) context);
    }

    /**
     * 设置预览Surface的角度
     *
     * @param width  宽度
     * @param height 高度
     */
    public void setAspectRatio(int width, int height) {
        if (width < 0 || height < 0) {
            throw new IllegalArgumentException("Size cannot be negative.");
        }
        mRatioWidth = width;
        mRatioHeight = height;
        requestLayout();
    }


    /**
     * 自定义View尺寸的规则
     *
     * @param widthMeasureSpec  horizontal space requirements as imposed by the parent.
     *                          The requirements are encoded with
     *                          {@link android.view.View.MeasureSpec}.
     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
     *                          The requirements are encoded with
     *                          {@link android.view.View.MeasureSpec}.
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (0 == mRatioWidth || 0 == mRatioHeight) {
            setMeasuredDimension(width, height);
        } else {
            if (width < height * mRatioWidth / mRatioHeight) {
                setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
            } else {
                setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
            }
        }
    }

}
